package de.alexhepp.widgets.messagewidget;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

public class SMSDao {

	public static final String SMS_CONTENT_INBOX = "content://sms/inbox";

	/** column that goes for SMS READ. */
	private static final String SMS_READ_COLUMN = "read";
	
	/** TAG used for Debug-Logging */
	public static final String LOG_TAG = "SMSDao";

	public static ArrayList<SMSMessage> getAllMessages(Context ctx) {

		return getMessages(ctx, null);
	}
	
	public static ArrayList<SMSMessage> getAllUnreadMessages(Context ctx) {

		return getMessages(ctx, SMS_READ_COLUMN + "=0");
	}
	

	private static ArrayList<SMSMessage> getMessages(Context ctx, String filter) {
		ArrayList<SMSMessage> messages = new ArrayList<SMSMessage>();

		Uri uri = Uri.parse(SMS_CONTENT_INBOX);
		Cursor c = ctx.getContentResolver().query(uri, null, filter, null, null);

		int bodyIndex = c.getColumnIndexOrThrow("body");
		int dateIndex = c.getColumnIndexOrThrow("date");
		int senderIdIndex = c.getColumnIndexOrThrow("person");
		int readIndex = c.getColumnIndexOrThrow("read");
		int numberIndex = c.getColumnIndexOrThrow("address");
		int messageIdIndex = c.getColumnIndexOrThrow("_id");

//		Log.i(LOG_TAG, "following indices:");
//		Log.i(LOG_TAG, "bodyIndex:" + bodyIndex);
//		Log.i(LOG_TAG, "dateIndex:" + dateIndex);
//		Log.i(LOG_TAG, "senderIdIndex:" + senderIdIndex);
//		Log.i(LOG_TAG, "readIndex:" + readIndex);
//		Log.i(LOG_TAG, "numberIndex:" + numberIndex);

		if (c.moveToFirst()) {
			for (int i = 0; i < c.getCount(); i++) {
				SMSMessage curMessage = new SMSMessage();
				try {

					curMessage.setBody(c.getString(bodyIndex).toString());
					curMessage.setNumber(c.getString(numberIndex).toString());
					curMessage.setDate(c.getLong(dateIndex));

					long senderId = c.getLong(senderIdIndex);
//					Log.v(LOG_TAG, "senderID:" + senderId);

					// TODO: the SMS content provider stores rawContactId for sms 
					// instead of contactId. change this!
					long contactId = MessageUtils.getContactIdFromPhoneNumber(ctx, curMessage.getNumber());
					
					// could not find a contact for the given number.
					if(contactId == -1){
						contactId = senderId;
					}
					
					curMessage.setSenderId(contactId);					
					
					curMessage.setRead(c.getString(readIndex).toString().equals("true"));
					curMessage.setMessageId(c.getLong(messageIdIndex));

					messages.add(curMessage);
					c.moveToNext();
				} catch (NullPointerException npe) {
					Log.e(LOG_TAG, "some bad index during sms retrieval");
				}
			}
		}
		c.close();
		return messages;
	}
}
